﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Galaktika.BI.Runtime;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.Controls.General;

using Ranet.AgOlap.Controls;
using Ranet.AgOlap.Controls.General;
using Ranet.AgOlap.Controls.MemberChoice.Info;
using Ranet.Olap.Core;
using Ranet.Olap.Core.Data;
using Galaktika.BI.Extensibility.Dom;
using Ranet.AgOlap.Controls.MemberChoice.ClientServer;
using Ranet.AgOlap.Commands;

namespace Galaktika.BI.Silverlight.Controls
{
    public partial class MemberChoicePanel : UserControl, IBindableObject, IEditableObject
    {
        public MemberChoicePanel()
        {
            InitializeComponent();

            this.AStep = 100;
            this.AUseStepLoading = true;
            this.AMultiSelect = true;
        }

        #region IBindableObject Members

        public IBindingContext Context { get; set; }

        private IDictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get 
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new SafeDictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }

        #endregion

        #region Свойства для настройки на OLAP
        /// <summary>
        /// Описание соединения с БД
        /// </summary>
        public string AConnection { get; set; }

        /// <summary>
        /// Имя OLAP куба
        /// </summary>
        public string ACubeName { get; set; }

        /// <summary>
        /// Выражение для под-куба
        /// </summary>
        public string ASubCube { get; set; }

        /// <summary>
        /// Имя иерархии измерения
        /// </summary>
        public string AHierarchyName { get; set; }

        public string AVariableToMDXSet { get; set; }

        public string AMemberVisualizationType { get; set; }
        private MemberVisualizationTypes MemberVisualizationType
        {
            get
            {
                if (!string.IsNullOrEmpty(this.AMemberVisualizationType))
                {
                    if (Enum.IsDefined(typeof(MemberVisualizationTypes), this.AMemberVisualizationType))
                    {
                        return (MemberVisualizationTypes)Enum.Parse(typeof(MemberVisualizationTypes), this.AMemberVisualizationType, false);
                    }
                }

                return MemberVisualizationTypes.Caption;
            }
        }

        #endregion Свойства для настройки на OLAP

        #region Частичная загрузка
        /// <summary>
        /// Шаг при частичной загрузке ("Задает шаг, используемый при частичной загрузке элементов")
        /// </summary>
        public int AStep { get; set; }


        /// <summary>
        /// Использование частичной загрузки ("Флаг указывает необходимость использования частичной загрузки элементов")
        /// </summary>
        public bool AUseStepLoading { get; set; }

        #endregion Частичная загрузка

        public bool ASelectLeafs { get; set; }

        /// <summary>
        /// Режим выбора: true - множественный выбор, false - одиночный выбор
        /// </summary>
        public bool AMultiSelect { get; set; }

        /// <summary>
        /// Уникальное имя уровня, начиная с которого элементы будут отображаться в дереве
        /// </summary>
        public string AStartLevelUniqueName { get; set; }

        /// <summary>
        /// Флажок. Выводить элементы ТОЛЬКО верхнего уровня
        /// </summary>
        public bool AShowOnlyFirstLevelMembers { get; set; }

        #region IEditableObject Members

        public void BeginEdit()
        {
            OlapDataLoaderEx loader = new OlapDataLoaderEx(this);
            loader.Context = this.Context;
            mcc.OlapDataLoader = loader;

            if (mcc.LogManager == null)
            {
                mcc.LogManager = new LogManagerEx(this.Context);
            }
        }

        public void CancelEdit()
        {
        }

        public void EndEdit()
        {
            if (string.IsNullOrEmpty(m_InternalName))
            {
                mcc.Connection = this.AConnection;
                mcc.CubeName = this.ACubeName;
                mcc.SubCube = this.ASubCube;
                mcc.HierarchyUniqueName = this.AHierarchyName;
                mcc.MultiSelect = this.AMultiSelect;
                mcc.UseStepLoading = this.AUseStepLoading;
                mcc.Step = this.AStep;
                mcc.StartLevelUniqueName = this.AStartLevelUniqueName;
                mcc.SelectedSet = string.Empty;
                mcc.ShowOnlyFirstLevelMembers = this.AShowOnlyFirstLevelMembers;
                mcc.MemberVisualizationType = this.MemberVisualizationType;
                mcc.Initialize();
            }
            m_InternalName = base.Name;
        }

        #endregion

        private string m_InternalName;

        private void mcc_ApplySelection(object sender, EventArgs e)
        {
            try
            {
                //Сохраняем в глобальную переменную
                IUserTaskManager taskManager = (IUserTaskManager)Context.Services.GetService(typeof(IUserTaskManager));
                if (taskManager != null)
                {
                    taskManager.RunTaskAsync(
                        string.Format(Localization.AppTask_ModificationVariable, AVariableToMDXSet), 
                        state => ModifyVariable(state), mcc.SelectedInfo);
                }
            }
            catch (Exception ex)
            {
                mcc.LogManager.LogException(this.Name, ex);
            }
        }

        private void ModifyVariable(object state)
        {
            List<MemberChoiceSettings> settings = (List<MemberChoiceSettings>)state;

            String set = String.Empty;
            if (settings != null)
            {
                set = mcc.SelectedSet;
            }

            String uniqueName = String.Empty;
            String caption = String.Empty;
            if (settings != null &&
                settings.Count == 1 &&
                settings[0].SelectState == Ranet.AgOlap.Controls.MemberChoice.Info.SelectStates.Selected_Self)
            {
                uniqueName = settings[0].UniqueName;
                caption = settings[0].Caption;
            }

            String variableName = AVariableToMDXSet;
            IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (context != null && !String.IsNullOrEmpty(variableName))
            {
                BrickVariable variable = context.GetVariable(this.Context, variableName);
                if (variable != null)
                {
                    context.ModifyVariable(this.Context, variableName, set);
                    variable.UserData[uniqueName] = caption;
                    variable.UserData[m_InternalName + "_SelectedInfo"] = mcc.SelectedInfo;
                }
            }
        }

        private void btnApply_Click(object sender, RoutedEventArgs e)
        {
            mcc_ApplySelection(sender, e);
        }
    }
}
